package io.halo.payment.channel.wxpay.v2;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * HaloPaymentConfig支付配置类
 *
 * @author: austin
 * @since: 2023/1/1 1:01
 */
@Component
public class HaloPaymentWxConfig extends AbstractWXPayConfig {

    /**
     * appId
     */
    @Value("${halo-pay.application.app-id}")
    private String appId;

    /**
     * 商户号
     */
    @Value("${halo-pay.application.mch-id}")
    private String mchId;

    /**
     * 秘钥
     */
    @Value("${halo-pay.application.mch-key}")
    private String mchKey;

    /**
     * 数据证书
     */
    @Value("${halo-pay.application.key-path}")
    private String certPath;

    private byte[] certData;

    /**
     * 读取数据证书内容到流
     *
     * @throws Exception
     */
    @PostConstruct
    private void init() throws Exception {
        File file = new File(certPath);
        FileInputStream fis = new FileInputStream(file);
        BufferedInputStream bis = new BufferedInputStream(fis);
        this.certData = new byte[(int) file.length()];
        bis.read(this.certData);
        bis.close();
    }

    @Override
    String getAppID() {
        return appId;
    }

    @Override
    String getMchID() {
        return mchId;
    }

    @Override
    String getKey() {
        return mchKey;
    }

    @Override
    InputStream getCertStream() {
        ByteArrayInputStream bis = new ByteArrayInputStream(this.certData);
        return bis;
    }

    @Override
    IWXPayDomain getWXPayDomain() {
        return new IWXPayDomain() {

            @Override
            public void report(String domain, long elapsedTimeMillis, Exception ex) {

            }

            @Override
            public DomainInfo getDomain(AbstractWXPayConfig config) {
                return new DomainInfo(WXPayConstants.DOMAIN_API, true);
            }
        };
    }
}
